package jack.com.servicekeep.service;

import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;

public class SmsObserver extends ContentObserver {

    private Handler mHandler;
    private Context mContext;

    long currentTime = 0L;
    long lastTimeOfUpdate = 0L;
    long threshold_time = 500;

    public SmsObserver(Context context,Handler handler) {
        super(handler);
        mContext = context;
        mHandler = handler;
    }

    @Override
    public void onChange(boolean selfChange, Uri uri) {
        super.onChange(selfChange, uri);

        Log.d("yanjun", "SmsObserver onChange uri:" + uri);

        if (uri == null || uri.toString().contains("content://sms/raw") || uri.toString().equals("content://sms")){
            return ;
        }

        //Uri inboxUri = Uri.parse("content://sms/inbox");
        Cursor c = mContext.getContentResolver().query(uri, null, null, null, "date desc");
        if (c != null) {
            if (c.moveToFirst()) {
                String body = c.getString(c.getColumnIndex("body"));

                currentTime = System.currentTimeMillis();

                if (currentTime - lastTimeOfUpdate < threshold_time) {
                    return;
                }

                lastTimeOfUpdate = currentTime;
                mHandler.obtainMessage(100, body).sendToTarget();
            }
            c.close();
        }
    }
}